import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  SafeAreaView,
  StatusBar,
  FlatList,
} from 'react-native';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';

// Simple text-based icons
const Icon = ({ name, size = 24, color = '#000' }: { name: string; size?: number; color?: string }) => {
  const iconMap: { [key: string]: string } = {
    'arrow-back': '⬅️',
    'circle': '●',
  };

  return (
    <Text style={{ fontSize: size, color, textAlign: 'center' }}>
      {iconMap[name] || '📱'}
    </Text>
  );
};

interface Application {
  id: string;
  type: string;
  title: string;
  details: string;
  applicationTime: string;
  status: string;
  data: any;
  category: string;
}

const MyApplications: React.FC = () => {
  const navigation = useNavigation();
  const [applications, setApplications] = useState<Application[]>([]);
  const [selectedCategory, setSelectedCategory] = useState('全部');

  const categories = ['全部', '人事管理', '行政事务', '财务类', '业务相关'];

  const loadApplications = async () => {
    try {
      const storedData = await AsyncStorage.getItem('applications');
      if (storedData) {
        const parsedData = JSON.parse(storedData);
        setApplications(parsedData);
      }
    } catch (error) {
      console.error('加载数据失败:', error);
    }
  };

  useFocusEffect(
    React.useCallback(() => {
      loadApplications();
    }, [])
  );

  const filteredApplications = applications.filter(app => {
    if (selectedCategory === '全部') return true;
    return app.category === selectedCategory;
  });

  const getStatusColor = (status: string) => {
    switch (status) {
      case '待审批':
        return '#ff4757';
      case '正在审批中':
        return '#2ed573';
      case '已通过':
        return '#2ed573';
      case '已拒绝':
        return '#ff4757';
      default:
        return '#747d8c';
    }
  };

  const renderApplicationItem = ({ item }: { item: Application }) => (
    <TouchableOpacity 
      style={styles.applicationItem}
      onPress={() => (navigation as any).navigate('Text', { application: item })}
    >
      <View style={styles.applicationHeader}>
        <View style={styles.titleContainer}>
          <Icon name="circle" size={12} color="#2196F3" />
          <Text style={styles.applicationTitle}>{item.title}</Text>
        </View>
        <Text style={[styles.statusText, { color: getStatusColor(item.status) }]}>
          {item.status}
        </Text>
      </View>
      <Text style={styles.applicationDetails}>{item.details}</Text>
      <Text style={styles.applicationTime}>申请时间: {item.applicationTime}</Text>
    </TouchableOpacity>
  );

  const renderCategoryTab = (category: string) => (
    <TouchableOpacity
      key={category}
      style={[
        styles.categoryTab,
        selectedCategory === category && styles.activeCategoryTab
      ]}
      onPress={() => setSelectedCategory(category)}
    >
      <Text style={[
        styles.categoryTabText,
        selectedCategory === category && styles.activeCategoryTabText
      ]}>
        {category}
      </Text>
    </TouchableOpacity>
  );

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor="#fff" />
      
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity 
          style={styles.backButton}
          onPress={() => navigation.goBack()}
        >
          <Icon name="arrow-back" size={20} color="#333" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>我的申请</Text>
        <View style={styles.headerSpacer} />
      </View>

      {/* Category Tabs */}
      <View style={styles.categoryTabs}>
        {categories.map(renderCategoryTab)}
      </View>

      {/* Applications List */}
      <FlatList
        style={styles.applicationsList}
        data={filteredApplications}
        renderItem={renderApplicationItem}
        keyExtractor={(item) => item.id}
        showsVerticalScrollIndicator={false}
        ListEmptyComponent={
          <View style={styles.emptyContainer}>
            <Text style={styles.emptyText}>暂无申请记录</Text>
          </View>
        }
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  backButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  headerSpacer: {
    width: 28,
  },
  categoryTabs: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  categoryTab: {
    flex: 1,
    alignItems: 'center',
    paddingVertical: 8,
  },
  activeCategoryTab: {
    borderBottomWidth: 2,
    borderBottomColor: '#2196F3',
  },
  categoryTabText: {
    fontSize: 14,
    color: '#666',
  },
  activeCategoryTabText: {
    color: '#2196F3',
    fontWeight: '600',
  },
  applicationsList: {
    flex: 1,
    paddingHorizontal: 16,
  },
  applicationItem: {
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  applicationHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  titleContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  applicationTitle: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
    marginLeft: 8,
  },
  statusText: {
    fontSize: 14,
    fontWeight: '500',
  },
  applicationDetails: {
    fontSize: 14,
    color: '#666',
    marginBottom: 4,
  },
  applicationTime: {
    fontSize: 12,
    color: '#999',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 60,
  },
  emptyText: {
    fontSize: 16,
    color: '#999',
  },
});

export default MyApplications;
